// eslint-disable-next-line no-undef
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 5274 });

// 存储所有连接和抢答状态
const clients = new Map();
const HEARTBEAT_INTERVAL = 30000; // 30秒
const HEARTBEAT_TIMEOUT = 60000; // 60秒

let canAnswer = false;
let firstResponder = null;

// 心跳检测定时器
setInterval(() => {
  const now = Date.now();
  clients.forEach((clientInfo, ws) => {
    if (now - clientInfo.lastPing > HEARTBEAT_TIMEOUT) {
      console.log(`客户端 ${clientInfo.userId} 连接超时，强制关闭`);
      ws.terminate();
      clients.delete(ws);
    } else if (now - clientInfo.lastPing > HEARTBEAT_INTERVAL) {
      if (ws.readyState === WebSocket.OPEN) {
        ws.ping();
      }
    }
  });
}, 5000);

wss.on('connection', (ws) => {
  console.log('新客户端连接');

  // 初始化客户端信息
  const clientId = `client_${Date.now()}`;
  clients.set(ws, {
    userId: clientId,
    isAdmin: false,
    lastPing: Date.now()
  });

  // 心跳响应处理
  ws.on('pong', () => {
    const clientInfo = clients.get(ws);
    if (clientInfo) {
      clientInfo.lastPing = Date.now();
    }
  });

  ws.on('message', (message = '') => {
    const str = Buffer.from(message).toString('utf8');
    console.log('接收到的消息', str)
    if (['ping', 'pong'].includes(str)) {
      return
    }
    const data = JSON.parse(str);
    const clientInfo = clients.get(ws);

    // 用户注册
    if (data.type === 'register') {
      clientInfo.userId = data.userId;
      clientInfo.isAdmin = data.isAdmin || false;
      return;
    }

    // 处理抢答
    if (data.type === 'answer' && canAnswer && !firstResponder) {
      firstResponder = data.userId;
      broadcast({ type: 'firstResponder', userId: data.userId });
    }

    // 管理员控制
    if (data.type === 'control' && clientInfo.isAdmin) {
      if (data.action === 'start') {
        canAnswer = true;
        firstResponder = null;
        broadcast({ type: 'status', status: '抢答开始' });
      } else if (data.action === 'reset') {
        canAnswer = false;
        firstResponder = null;
        broadcast({ type: 'status', status: '抢答已重置' });
      }
    }
  });

  ws.on('close', () => {
    console.log(`客户端 ${clients.get(ws)?.userId} 断开连接`);
    clients.delete(ws);
  });
});

function broadcast(message) {
  wss.clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify(message));
    }
  });
}
